function showLoading(){
	showLoading.Loading = showLoading.Loading||$('<div class="showloading"><div><img src="http://ued.paixie.net/images/public/loading.gif" width="32" height="32"><br/>正在加载请稍后...</div></div>').appendTo('body');
	showLoading.Loading.show();
};
showLoading.hide = function(){
	try{
		showLoading.Loading.hide();
	}catch (e){}
};
var ImgCache = {
	ImgList	:{},
	GetCache:function(goodid,src){
		if(ImgCache.ImgList[goodid]==null){
			var img = new Image();
			img.src = src;
			ImgCache.ImgList[goodid] = img;
		}
		return ImgCache.ImgList[goodid];
	}
};
function AjaxRun(act,data,callback,isonly,url){
	if(act!='init'){
		showLoading();
	}
        var str = '';
        if(window.location.href.indexOf('?') == -1)
        {
            str = '?'+new Date().getTime();
        }else{
			str = '&'+new Date().getTime();
		}
	url = url||window.location.href+str;
  
	var _SendDataIndex = 0;
	if(isonly){
		if(++AjaxRun.SendDataIndex>999999){AjaxRun.SendDataIndex=0;}
		var _SendDataIndex = AjaxRun.SendDataIndex;
	}
	data = data||{};
	data.address = {
		id		:$.trim($('#js-trolly-address-id').val()),
		province	:$.trim($('#js-trolly-address-province').text()),
		city		:$.trim($('#js-trolly-address-city').text()),
		area		:$.trim($('#js-trolly-address-area').text()),
		phone		:$.trim($('#js-trolly-address-phone').text()),
		address		:$.trim($('#js-trolly-address-address').text()),
		name		:$.trim($('#js-trolly-address-name').text()),
		zipcode		:$.trim($('#js-trolly-address-zipcode').text())
	};

	data.act = act;
    
	$.ajax({url:url,type:'post',data:data,
	   error:function(a){
		if(isonly&&_SendDataIndex != AjaxRun.SendDataIndex){
			return;
		}
		if(callback){
			callback({IsSuccess:false,Message:'链接服务器失败！'});
		}
	},success:function(data){
		if(isonly&&_SendDataIndex != AjaxRun.SendDataIndex){
			return;
		}
                
		try{
			data = $.parseJSON($.trim(data.replace(/^[^{]+/,'')));
		}catch (e){callback({IsSuccess:false,Message:'链接服务器失败！'});}
		if(isonly){
			if(_SendDataIndex == AjaxRun.SendDataIndex){
				if(callback){
					callback(data);
				}
			}
		}else{
			if(callback){
				callback(data);
			}
		}
	}});
};
var oldcards;
AjaxRun.SendDataIndex = 0;
$(document).ready(function(e) {
	if(Business==null){
		//window.location.href = "index";
		return;
	}
	var sendData = {
		"act"		:"init",
		"business"	:Business,
		"address"	:null,
		"paytype"	:null,
		"pxgold"	:0,
		"message"	:""
	};
     
	/*拍鞋币*/
	var PXGold = {
		Max:0,
		Use:0
	};
	/*购物车数据*/
	var CartData = null;
        
	var BusinessTemplate = template.compile($("#js-business-template").html());
	function BuildHtml(){
		CartData.toFixed=function(val){return parseFloat(val).toFixed(2);}
		$("#js-item-list").html(BusinessTemplate({data:CartData}));
		$("#js-item-list a[src]").each(function(){
			$(this).append(ImgCache.GetCache($(this).attr('goodid'),$(this).attr('src')));
		});
	};
	function AjaxEnd(data){
		showLoading.hide();
		
		if(data.IsSuccess) CartData = data.data;
		
		if(CartData.gold_message) alert(CartData.gold_message);
		
		//绑定全场优惠
		var key, counter = 0;
		for(key in CartData.offersList) counter++;
		if (counter>0){
			if (CartData.offers.id) {
				var htitle=CartData.offersList[CartData.offers.id].offertitle;
				var hprice=CartData.offers.price.toFixed(2);
                                
                               
                
			}else{
				var htitle='不使用优惠'	
				var hprice='0.00';
			}
			var html='<p >全网优惠：<span class="pxui-select"><span>'+htitle+'</span><i></i><select class="offer" business-id="all" brand-id="all" id="js-offer-business-all-brand-all"><option value="0">不使用优惠</option>'
			var offerCount = 0;
			for(var offer in CartData.offersList){
			offer =CartData.offersList[offer];
			if(offer.type=='card')offerCount++;
				html+='<option value="'+offer.offerid+'" '
				if(CartData.offers.id==offer.offerid){
					  html+='selected'
					  sendData.offers = {"offerid":CartData.offers.id};	

				} 
				html+=' >'+offer.offertitle+'</option>'
			}
			html+='</select></span><b>-'+hprice+'</b></p>'
                        total_offer_price += parseFloat(hprice);
			if ($('#js-all-offers p').length>0)$('#js-all-offers p').remove();
			$('#js-all-offers').prepend(html);
			if(CartData.offers_all===false){
				$('#js-offer-business-all-brand-all').find('option:gt(0)').remove().end().parent().css({'opacity':0.5}).click(function(){
					alert('Q券(全网优惠)不能和Z券(自营优惠)同时使用');
				}).find('span').html('不使用优惠');
			}
		}else{
			if ($('#js-all-offers p').length>0) $('#js-all-offers p').remove();
		}
		//绑定全场优惠-end
		
		
		
		
		if(data.IsSuccess){
			CartData = data.data;
			sendData.offers_all = (CartData.offers_all==null)?true:CartData.offers_all;
			sendData.offers_brand = (CartData.offers_brand==null)?true:CartData.offers_brand;
			switch (CartData.act){
				case 'init':
					$("#js-trolly-loading").hide();
					$("#js-trolly").fadeIn();
//					$.each(CartData.business,function(businessid,business){
//						//免费的并且没有尺码或者尺码只有一个的-赠品-自动帮用户选择
//						$.each(business.giftsList,function(giftid,gift){
//							if(gift.price==0&&gift.sizes.length<=1){
//								if(!gift.sizes.length){
//									CartData.business[businessid].gifts[giftid] = {"brandid":gift.brandid,"giftid":giftid,"sizeid":""};
//						  		}else{
//									CartData.business[businessid].gifts[giftid] = {"brandid":gift.brandid,"giftid":giftid,"sizeid":gift.sizes[0].sizeid};
//								}
//							}
//						});
//						//免费的并且没有尺码或者尺码只有一个的-赠品-自动帮用户选择-end
//					});
				break;
			}
			$.each(CartData.business,function(businessid,business){
				//矫正选择的快递
				/*if(business.express!=null){
					$.each(business.expressList,function(expressid,express){
						business.express = expressid;
						return false;
					});
				}*/
				//矫正选择的快递-end
				//移除失效赠品
				//alert(typeof(business));
				if(typeof(business.gifts)!="undefined"){
				$.each(business.gifts,function(giftid,gift){
					if(!business.giftsList[giftid]){
						delete CartData.business[businessid].gifts[giftid];
					}
				});
				}
				//移除失效赠品-end
				//自动添加不使用优惠选项
				if(typeof(business.offersList)!="undefined"){
				$.each(business.offersList,function(brandid,brand){
					var offers = CartData.business[businessid].offersList[brandid].offers;
					CartData.business[businessid].offersList[brandid].offers = {"0":{"offerid":"0","offertitle":"不使用优惠","offerdetail":"","price":0}};
					$.each(offers,function(offerid,offer){
						CartData.business[businessid].offersList[brandid].offers[offerid] = offer;
					});
					offers = null;
				});
				}
				//自动添加不使用优惠选项-end
			});
			CartData.toFixed=function(val){return parseFloat(val).toFixed(2);}
			BuildHtml();
			if(CartData.offers_brand===false){
				$('.pxui-select-offers select').each(function(){
					$(this).find('option:gt(0)').remove().end().parent().css({'opacity':0.5}).click(function(){
						alert('Q券(全网优惠)不能和Z券(自营优惠)同时使用');
					}).find('span').html('不使用优惠');
				});
			}
			switch (CartData.act){
				case 'useoffercard':  
					var _businessid="",_brandid="";
					var issuccess = false;
					$.each(CartData.business,function(businessid,business){
						$.each(business.offers,function(brandid,offer){
							if(offer.offerid === oldcards){
								_businessid = businessid;
								_brandid = brandid;
								issuccess = true;
								return false;
							}
						});
						if(issuccess){
							return false;
						}
					});
					if(CartData.offersList != null){
					    $.each(CartData.offersList,function(oid,offer){
						if(CartData.offers != '' && CartData.offers != null && oid == CartData.offers.id && oldcards == CartData.offers.id){
							_businessid = 'all';
							_brandid = 'all';
							CartData.offersid = oid;
							issuccess = true;
							return false;
						}
						if(issuccess){
							return false;
						}
					    });
                                        }
					if(issuccess){
							if ($("#js-use-card-button").attr('rel')==undefined){
								$("#js-use-card-button").attr('rel',oldcards)
							}else {
								$("#js-use-card-button").attr('rel',$("#js-use-card-button").attr('rel')+','+oldcards)
							}
						
						
						var obj = $("#js-offer-business-"+_businessid+"-brand-"+_brandid).parent().parent();
						var top = $("#js-offer-business-"+_businessid+"-brand-"+_brandid).offset().top;
						setTimeout(function(){
							obj.css({'background-color':'#fff'});
							setTimeout(function(){
								obj.css({'background-color':'#FB4E3A'});
								setTimeout(function(){
									obj.css({'background-color':'#fff'});
								},500);
							},500);
						},500);
						obj.css({'background-color':'#FB4E3A'});
						if(getScroll().t>top){
							if (document.documentElement && document.documentElement.scrollTop) {
								document.documentElement.scrollTop = top-$(window).height()/2;
							} else if (document.body) {
								document.body.scrollTop = top-$(window).height()/2;
							}
						}
					}else{
                                                sendData.offercart = '';
						alert(data.Message||"优惠券不可用！");
                                                
					}
                                        
				break;
			}
		}else{
			if(CartData){
				BuildHtml();
				alert(data.Message);
			}else{
				alert(data.Message);
				//window.location.href = 'index';
				return false;
			}
		}
		//绑定拍鞋币数据
		PXGold.Max = CartData['max-pxgold']||0;
		PXGold.Use = CartData['use-pxgold']||0;
		if(PXGold.Max!='0'){
			$('#js-use-pxgold-button').show();
		}else{
			$('#js-use-pxgold-button').hide();
		}
		var __price = (CartData['pxgold']/100).toFixed(2);
		$("#js-use-pxgold").html('￥-'+__price);
		if(CartData['pxgold']){
			$('#js-use-pxgold-button').html('已使用'+CartData['pxgold']+'个拍鞋币(抵扣'+__price+'元)<i class="arrow-right"></i>');
		}else{
			$('#js-use-pxgold-button').html('使用拍鞋币<i class="arrow-right"></i>');
		}
		if(CartData['pxgold']==0){
			$('#js-pxgold-show-box').hide();
		}else{
			$('#js-pxgold-show-box').show();
		}
		$("#js-get-pxgold").html(CartData['get-pxgold']);
                
                // 删除优惠显示信息
                $('.js-offers-show-box').remove();
                // 删除优惠显示信息
                $('.js-ship-show-box').remove();
                // 删除手续费
                $('.js-service-show-box').remove();
                
                var good_nums = 0;
                var ship_cost = 0;
                var total_offer_price = 0;
                var service_amount = 0;
                
                $("#js-goodtotal-text").html('￥'+CartData['get-pxgold'].toFixed(2));
		//绑定拍鞋币数据-end
		$("#js-total-text").html('￥'+CartData.total.toFixed(2));
		
		//整理发送数据
		sendData.business = {};
		$.each(CartData.business,function(businessid,business){
			if(!business||!business.items){
				window.location.reload();
			}
			sendData.business[businessid] = {};
			sendData.business[businessid]['items'] = {};
			$.each(business.items,function(itemid,_item){
				sendData.business[businessid]['items'][itemid] = {};
				sendData.business[businessid]['items'][itemid]['itemid'] = _item.itemid;
				sendData.business[businessid]['items'][itemid]['num'] = _item.num;
				sendData.business[businessid]['items'][itemid]['sizeid'] = _item.sizeid;
				if(typeof(_item.tuan_id) != 'undefined' && _item.tuan_id != '' && _item.tuan_id != null){
				   sendData.business[businessid]['items'][itemid]['tuan_id'] = _item.tuan_id; 
				}
				// 商品数量 ，该js为程序员添加的
				good_nums += parseInt(_item.num);
                                
			});
			if(typeof(business.gifts) != "undefined"){
				sendData.business[businessid]['gifts'] = business.gifts;
			}
			if(typeof(business.offers) != "undefined"){
				sendData.business[businessid]['offers'] = business.offers;
			}
			if(typeof(business.express) != "undefined"){
				sendData.business[businessid]['express'] = business.express;
			}
                        
                        if(business.giftsList != ''){
                            for(var d in business.giftsList){
                                good_nums += 1;
                            }                          
                        }
                        
                        
                        // 优惠券信息 有问题请咨询程序员。该js为程序员添加的
                        
                        for(var o in business.offers)
                        {
                            var offer_item = business.offers[o];
                            if(offer_item.price > 0){
                                var offer_price = parseFloat(offer_item.price);
                                var offer_key   = offer_item.brandid;
                                var offer_id    = offer_item.offerid;
                                var offer_name  = business.offersList[offer_key]['offers'][offer_id]['offertitle'];
                                total_offer_price += offer_price;
                            }                            
                        }
                        // 


                        
                        
                        // 邮费 有问题请咨询程序员。该js为程序员添加的
                        for(var i in business.expressList){
                            if(i == business.express){
                                ship_cost += parseFloat(business.expressList[i]['price']);
                            }
                        } 
						
                        // 货到付款手续费
                        if(business.CashDelivery){
                            service_amount = Number(service_amount) + Number(business.CashDelivery.price) ;
                        }
		});
                var key, counter = 0;
		for(key in CartData.offersList) counter++;
		if (counter>0){
			if (CartData.offers.id) {
//				var htitle=CartData.offersList[CartData.offers.id].offertitle;
//				var hprice=CartData.offers.price.toFixed(2);
                                total_offer_price += parseFloat(hprice);
                               
                
			}else{
//				var htitle='不使用优惠'	
//				var hprice='0.00';
			}  
                }
                
                if(parseInt(total_offer_price) > 0){
                      var offer_htm   = '<li class="js-offers-show-box">优惠金额：<b class="pxui-color-red" >￥-'+total_offer_price.toFixed(2)+'</b></li>';
                      $('.total ul').append(offer_htm);    
                } 
                if(parseInt(service_amount) > 0){
                      var offer_htm   = '<li class="js-service-show-box">手<i style="padding: 0 0 0 0.5em;"></i>续<i style="padding: 0 0 0 0.5em;"></i>费：<b class="pxui-color-red" >￥'+Number(service_amount).toFixed(2)+'</b></li>';
                      $('.total ul').append(offer_htm);    
                }    
                    
                ship_cost = ship_cost.toFixed(2).toString();
                $('#js-goodnums-text').html(good_nums+'件');
                $('#js-shipcost-text').html('￥+'+ship_cost);
		sendData.paytype = CartData.paytype;
		if(!sendData.paytype){
			sendData.paytype = {type:1,bank:200};
		}
		if(!CartData.isCashDelivery){
			if(sendData.paytype.type==4){
				sendData.paytype = {type:1,bank:200};
			}
			$('#js-pay-4').hide();
		}else{
			$('#js-pay-4').show();
		}
		if(sendData.paytype.type==4){
			sendData.paytype.bank = '';
		}
		var display = $("#js-paytype a[value='"+sendData.paytype.type+','+sendData.paytype.bank+"']").css('display');
		if(!display || display=='none'){
			var pay = $("#js-pay-1").attr('value').split(',');
			sendData.paytype = {type:pay[0],bank:pay[1]};
		}
		$("#js-paytype a[value='"+sendData.paytype.type+','+sendData.paytype.bank+"']").click();
		sendData.pxgold = CartData.pxgold;
		sendData.address = CartData.address;
	};
	AjaxRun("init",sendData,AjaxEnd,true);
	/*支付方式*/
	$("#js-paytype a").click(function(){
		if($(this).hasClass('selected'))return;
		$(this).addClass('selected').siblings('a.selected').removeClass('selected');
		var pay = $(this).attr('value').split(',');
		sendData.paytype.type = pay[0];
		sendData.paytype.bank = pay[1];
		AjaxRun("init",sendData,AjaxEnd,true);
	});
	/*支付方式-end*/
	/*改变数量*/
	$('#js-item-list').delegate('ul select','change',function(){
		sendData.business[$(this).attr('business-id')].items[$(this).attr('item-id')].num = $(this).val();
		AjaxRun("init",sendData,AjaxEnd,true);
	});
	/*改变数量-end*/
	/*改变优惠*/
	$('#js-item-list').delegate('select.offer','change',function(){
		var businessid = $(this).attr("business-id");
		var brandid = $(this).attr("brand-id");
		sendData.business[businessid].offers[brandid] = {"brandid":brandid,"offerid":$(this).val()};
                // changeoffer
		AjaxRun("init",sendData,AjaxEnd,true);
	});
	$('.alloffer').delegate('select.offer','change',function(){
		sendData.offers = {"offerid":$(this).val()};
         // changeoffer
		AjaxRun("init",sendData,AjaxEnd,true);
	});
	/*改变优惠-end*/
	/*改变快递*/
	$('#js-item-list').delegate('select.express','change',function(){
		sendData.business[$(this).attr("business-id")].express = $(this).val();
		AjaxRun("init",sendData,AjaxEnd,true);
	});
	/*改变快递-end*/
	/*使用拍鞋币*/
	$('#js-use-pxgold-button').click(function(){
		var buttons = [];
		var pricetotal=CartData['get-pxgold'];
		var golduse=(CartData.pxgold||PXGold.Use);
		var text = '您有拍鞋币'+PXGold.Max+'个，本次消费可使用'+PXGold.Use+'个拍鞋币（抵用现金￥'+(PXGold.Use/100)+'元）';
		if(pricetotal<50){
			 text = '您有拍鞋币'+PXGold.Max+'个，不满50元不可使用拍鞋币';
			 golduse = 0;
			}
		if(PXGold.Max<100){
			text='您有拍鞋币'+PXGold.Max+'个，本次消费可使用'+PXGold.Use+'个拍鞋币（抵用现金￥'+(PXGold.Use/100)+'元），集满100个可抵扣1元哦！'
			}
		if(PXGold.Max<100||pricetotal<50){
			buttons = [
				{
					light	:true,
					text	:'  确 认  ',
					click	:function(){
						msgbox.close();
					}
				}
			];
		}else{
			buttons = [
				{
					light	:true,
					text	:'  使 用  ',
					click	:function(){
						var value = $.trim($('#js-use-pxgold-box').val());
						if(value==''){value = 0;};
						if(/^\d+$/.test(value)){
							value = parseInt(value/100)*100;
							sendData.pxgold = value;
							AjaxRun("init",sendData,AjaxEnd,true);
							msgbox.close();
						}else{
							alert('您请输入数字！');
						}
					}
				},
				{
					light	:false,
					text	:'  取 消  ',
					click	:function(){
						msgbox.close();
					}
				}
			];
		}
		var msgbox = $.message({
			html 	:	'<div>'+
							'<input id="js-use-pxgold-box" style="width: 99%;display: block;margin: 6px 0;padding: 8px 0;text-indent: 8px;" type="text" value="'+ golduse +'" max="'+PXGold.Use+'"/>'+
							text+
						'</div>',
			title	: '使用拍鞋币',
			height	: 'auto',
			buttons	: buttons
		});
	});
	/*使用拍鞋币-end*/
	/*使用优惠券*/
	$('#js-use-card-button').click(function(){
		var msgbox = $.message({
			html 	:	'<div>'+
							'<input id="js-use-card-box" style="width: 99%;display: block;margin: 6px 0;padding: 8px 0;text-indent: 8px;" type="text"/>'+
						'</div>',
			title	: '使用优惠券',
			height	: 'auto',
			buttons	: [
				{
					light	:true,
					text	:'  使 用  ',
					click	:function(){
						var value = $.trim($('#js-use-card-box').val());
						if(value==''){
							return msgbox.close();
						};
						oldcards=value;
						//sendData.offercart = value;
						if ($("#js-use-card-button").attr('rel')==undefined){
							sendData.offercart = value;
						}else {
							sendData.offercart = $("#js-use-card-button").attr('rel')+','+value;
						}
						AjaxRun("useoffercard",sendData,AjaxEnd,true);
						 msgbox.close();
					}
				},
				{
					light	:false,
					text	:'  取 消  ',
					click	:function(){
						msgbox.close();
					}
				}
			]
		});
	});
	/*使用优惠券-end*/
	/*选择赠品*/
	$('.sizes a').live('click',function(){
		$(this).addClass('selected').siblings('a.selected').removeClass('selected');
	});
	$('.js-grft-select').live('click',function(){
		var businessid = $(this).attr('business-id');
		var giftid = $(this).attr('gift-id');
		var sizes = CartData.business[businessid].giftsList[giftid].sizes;
		var price = CartData.business[businessid].giftsList[giftid].price;
		var sizeid = CartData.business[businessid].gifts[giftid];
		if(sizeid){
			sizeid = sizeid.sizeid;
		}else{
			sizeid = '';
		}
		var html = '';
		var title = '';
		if(price==0){
			title = '选择尺码';
			if(!sizes||sizes.length<=1){
				if(sizes.length){
					sizeid = sizes[0].sizeid;
				}
				sendData.business[businessid].gifts[giftid] = {"brandid":CartData.business[businessid].giftsList[giftid].brandid,"giftid":giftid,"sizeid":sizeid};
				return AjaxRun("selectgift",sendData,AjaxEnd,true);
			}
		}else{
			title = '选择换购';
			html+='<p style="font-size: 16px;padding-left: 5px;">换购说明：加'+price+'元可换购此商品</p>';
		}
		if(sizes&&sizes.length>1){
			html+='<div id="js-sizes-box" class="sizes">';
			$.each(sizes,function(index,value){
				
				html+='<a '+((sizeid==value.sizeid)?'class="selected"':'')+' sizeid="'+value.sizeid+'">'+value.size+'</a>';
			});
			html+='</div>';
		}else if(sizes){
			if(sizes.length){
				sizeid = sizes[0].sizeid;
			}
		}
		var msgbox = $.message({
			html 	: html,
			title	: title,
			height	: 'auto',
			buttons	: [
				{
					light	:true,
					text	:'  选 择  ',
					click	:function(){
						if($('#js-sizes-box').length){
							if(!$('#js-sizes-box a.selected').length){
								return alert('请先选择尺码！');
							}
							sendData.business[businessid].gifts[giftid] = {"brandid":CartData.business[businessid].giftsList[giftid].brandid,"giftid":giftid,"sizeid":$('#js-sizes-box a.selected').attr('sizeid')};
						}else{
							sendData.business[businessid].gifts[giftid] = {"brandid":CartData.business[businessid].giftsList[giftid].brandid,"giftid":giftid,"sizeid":sizeid};
						}
						AjaxRun("selectgift",sendData,AjaxEnd,true);
						msgbox.close();
					}
				},
				{
					light	:false,
					text	:'  取 消  ',
					click	:function(){
						msgbox.close();
					}
				}
			]
		});
	});
	$('.js-gift-del').live('click',function(){
		var businessid = $(this).attr('business-id');
		var giftid = $(this).attr('gift-id');
		if(confirm($(this).text().replace("不要","您确定不要该")+'？')){
			delete sendData.business[businessid].gifts[giftid];
			AjaxRun("cancelgift",sendData,AjaxEnd,true);
		}
	});
	/*选择赠品-end*/
	/*手机验证*/
	window['VerifyPhone'] = window['VerifyPhone']||'';
	(function(){
       
		var phoneerror = '';
		var codeerror = '';
		var SendPhoneCodeIndex = 0;
		var VerifyPhoneCodeIndex = 0;
		function setPhoneTip(isnoerror){
			if(!phoneerror){
				$(this).next().html('&nbsp;').css({'opacity':0.5,'color':'#575757'});
				$('#js-trolly-get-code').prop('disabled',false);
                var phone_msg = '为能提供更优质的服务，拍鞋网需要验证您的手机号。';
               $('#js-verify-phone-box .error-msg').html(phone_msg);
			}else{
                  	phoneerror = $.trim(phoneerror);
				if(isnoerror){
					$(this).next().css({'opacity':0.5,'color':'#575757'});
				}else{
					//$(this).next().html(phoneerror).css({'opacity':1,'color':'red'});
                    $(this).next().css({'opacity':0.5,'color':'#575757'});
				} 
                                
				if(phoneerror == '该手机已存在，请登录！'){
					var phone_msg = '手机号已被注册，您可以<a href="/login/?mode=unlogin&url=/order/trolly">直接登录</a>或者换个手机号再试试';
					$('#js-verify-phone-box .error-msg').html(phone_msg);
				}
				$('#js-trolly-get-code').prop('disabled',true);
			}
			$('#js-trolly-code').val('');
			clearInterval($('#js-trolly-get-code').data('Interval'));
			SendPhoneCodeIndex++;
			VerifyPhoneCodeIndex++;
			$('#js-trolly-get-code').val('获取手机验证码');
			$('#js-trolly-verify,#js-trolly-code').prop('disabled',true);
			$('#js-trolly-verify').val('验证手机号码');
		};
		function setCodeTip(isnoerror){
			if(!codeerror){
				$(this).next().html('&nbsp;').css({'opacity':0.5,'color':'#575757'});
				$('#js-trolly-verify').prop('disabled',false);
			}else{
				if(isnoerror){
					$(this).next().html(codeerror).css({'opacity':0.5,'color':'#575757'});
				}else{
					$(this).next().html(codeerror).css({'opacity':1,'color':'red'});
				}
				$('#js-trolly-verify').prop('disabled',true);
			}
		};
		$('#js-trolly-phone').change(function(){
			var self = this;
			var phone = $(self).val($.trim($(self).val())).val();
			phoneerror = PXVerify.Phone(phone,true,function(isok,error){
				phoneerror = error;
				setPhoneTip.call(self);
			});
                        
			if(phoneerror){
				setPhoneTip.call(self);
			}else{
				phoneerror = '正在联网验证手机号码，请稍后!';
				setPhoneTip.call(self,true);
			}
		});
		$('#js-trolly-get-code').click(function(){
			if($(this).prop('disabled'))return;
			var self = this;
			var phone = $('#js-trolly-phone').val();
			var _SendPhoneCodeIndex = 0;
			phoneerror = PXVerify.SendPhoneCode(phone,false,function(isok,error){
				if(_SendPhoneCodeIndex!=SendPhoneCodeIndex)return;
				if(isok){
					$('#js-trolly-code').prop('disabled',false).focus();
					var time = 60;
					$(self).val('60秒后重新发送').data('Interval',setInterval(function(){
						if(--time<=0){
							clearInterval($(self).val('获取验证码').prop('disabled',false).data('Interval'));
							return;	
						}
						$(self).val(time+'秒后重新发送');
					},1000));
				}else{
					alert(error);
                    $(self).val('获取手机验证码').prop('disabled',false);
				}
                               
			});
			setPhoneTip.call('#js-trolly-phone');
			_SendPhoneCodeIndex = SendPhoneCodeIndex;
			if(!phoneerror){
				$(self).val('正在发送验证码...').prop('disabled',true);
			}
		});
		$('#js-trolly-code').change(function(){
			var self = this;
			var code = $(self).val($.trim($(self).val())).val();
			var phone = $('#js-trolly-phone').val();
			codeerror = PXVerify.PhoneCode(phone,code,false);
			setCodeTip.call(self);
		});
		$('#js-trolly-verify').click(function(){
			if($(this).prop('disabled'))return;
			var self = this;
			var code = $('#js-trolly-code').val();
			var phone = $('#js-trolly-phone').val();
			var _VerifyPhoneCodeIndex = 0;
			codeerror = PXVerify.PhoneCode(phone,code,true,function(isok,error){
				if(_VerifyPhoneCodeIndex!=VerifyPhoneCodeIndex)return;
				$('#js-trolly-code').prop('disabled',false);
				$(self).val('验证手机号码').prop('disabled',false);
				if(isok){
					window['VerifyPhone'] = phone;
                                        window['VerifyCode'] = code;
					clearInterval($('#js-trolly-get-code').data('Interval'));
     
					$('#js-verify-phone-box').html('<div style="padding: 10px 20px;"><strong class="pxui-color-red">恭喜您！手机验证成功！</strong><br/>当前手机号码为：'+phone+'</div>');
				}else{
					alert(error);
				}
                                
			});
			setCodeTip.call('#js-trolly-code');
			_VerifyPhoneCodeIndex = VerifyPhoneCodeIndex;
			if(!codeerror){
				$('#js-trolly-code').prop('disabled',true);
				$(self).val('正在验证...').prop('disabled',true);
			}
		});
	})();
	/*手机验证-end*/
	/*改变收货地址*/
	(function(){
            
		$('#js-other-use-address,#js-other-use-address-2').click(function(){
			if($('#js-address-page').length){
				$('#js-address-page').show().siblings().hide();
				document.body.scrollTop = 0;
				if(!$('#js-address-page div.pxui-area a').length){
					$('#js-address-page .page-title a:last').click();
				}
			}else{
				showLoading();
				$.ajax({url:'/member/address.php?act=index&ajax=1',success:function(data){
					$(data).insertAfter($('#js-cart-trolly-page').hide()).attr('id','js-address-page');
					showLoading.hide();
					document.body.scrollTop = 0;
					if ($('#js-address-page .pxui-noitem').text()=='您还未添加任何收货地址！') $('#js-address-page').hide();
					
				}});
			}
		});
		function setAddress(id,zipcode,name,phone,province,city,area,address){
			$('#js-trolly-address-id').parent().show().prev().hide();
			$('#js-trolly-address-id').val(id);
			$('#js-trolly-address-zipcode').text(zipcode);
			$('#js-trolly-address-name').text(name);
			$('#js-trolly-address-phone').text(phone);
			$('#js-trolly-address-province').text(province);
			$('#js-trolly-address-city').text(city);
			$('#js-trolly-address-area').text(area);
			$('#js-trolly-address-address').text(address);
			$('#js-cart-trolly-page').show().siblings().hide();
			document.body.scrollTop = $('#js-other-use-address').parent().prev().offset().top;
			sendData.address = {
				"id"		:id,
				"province"	:province,
				"city"		:city,
				"area"		:area,
				"phone"		:phone,
				"zipcode"	:zipcode,
				"address"	:address,
				"name"		:name
			};
			AjaxRun("init",sendData,AjaxEnd,true);
		};
		function loadAddressInfo(address){
			address = address || {
				id		:'',
				zipcode	:'',
				realname	:'',
				phone	:'',
				location:'',
				default	:false,
				province:'',
				city	:'',
				area	:''
			};
			if($('#js-address-info-page').length){
                           
				$('#js-address-info-page').show().siblings().hide();
				window['address-info'] = address;
				window['AddressInfoInit']();
				document.body.scrollTop = 0;
         
			}else{
				showLoading();
				var address_url = '';
				if(typeof(address.id) == 'undefined' || address.id == null || address.id == ''){
					 address_url = '/member/address?act=add&ajax=1'
				}else{
					 address_url = '/member/address?act=edit&id='+address.id+'&ajax=1';
				}
      
				$.ajax({url:address_url,success:function(data){
				        $(data).insertAfter($('#js-cart-trolly-page')).attr('id','js-address-info-page').siblings().hide();       
                                        showLoading.hide();
					document.body.scrollTop = 0;
					window['address-info'] = address;
					window['AddressInfoInit']();
				}});
                           
			}
		};
		/*添加或修改地址成功*/
		window['address-info-success'] = function(address){

			var a = $('#js-address-'+address.id);
                        
			if(a.length){
				a.find('.address-id').val(address.id),
				a.find('.address-zipcode').text(address.zipcode),
				a.find('.address-name').text(address.realname),
				a.find('.address-phone').text(address.phone),
				a.find('.address-province').text(address.province),
				a.find('.address-city').text(address.city),
				a.find('.address-area').text(address.area),
				a.find('.address-address').text(address.location)
			}else{
				var list = $('#js-address-page .pxui-list');
				var html = '<a id="js-address-'+address.id+'" for="js-address-'+address.id+'"> '+
					'<input type="hidden" value="'+address.id+'" class="address-id"> '+
					'<span class="address-realname">'+address.realname+'</span> <span class="address-phone">'+address.phone+'</span><br> '+
					'<span class="address-province">'+address.province+'</span> '+
					'<span class="address-city">'+address.city+'</span> '+
					'<span class="address-area">'+address.area+'</span> '+
					'<span class="address-location">'+address.location+'</span><br> '+
					'<span class="address-zipcode">'+address.zipcode+'</span> '+
					'</a> '+
					'<p><a for="js-address-'+address.id+'" class="pxui-light-button">修改并选择</a><a for="js-address-'+address.id+'" class="pxui-blue-button">选择</a></p> ';
				if(list.length){
					list.append(html);
				}else{
					$('#js-address-page .pxui-area').html('<div class="pxui-list" data-model="radio">'+html+'</div>');
				}
				html = null;
			}
			setAddress(address.id,address.zipcode,address.realname,address.phone,address.province,address.city,address.area,address.location);
		};
		/*修改并使用*/
		$('.address-page .pxui-list .pxui-light-button').live('click',function(){
			var a = $('#'+$(this).attr('for'));
			loadAddressInfo({
				id		:a.find('.address-id').val(),
				zipcode	:a.find('.address-zipcode').text(),
				realname	:a.find('.address-realname').text(),
				phone	:a.find('.address-phone').text(),
				province:a.find('.address-province').text(),
				city	:a.find('.address-city').text(),
				area	:a.find('.address-area').text(),
				location:a.find('.address-location').text(),
				default	:a.find('.address-default').prop('checked')
			});
            $('#js-save').val('保存并选择');
			$('.showloading,#js-address-page').hide();
			return false;
		});
		/*使用*/
		$('.address-page .pxui-list .pxui-blue-button,.address-page .pxui-list > a').live('click',function(){
			$(this).next().show();
			var a = $('#'+$(this).attr('for'));
			setAddress(
				a.find('.address-id').val(),
				a.find('.address-zipcode').text(),
				a.find('.address-realname').text(),
				a.find('.address-phone').text(),
				a.find('.address-province').text(),
				a.find('.address-city').text(),
				a.find('.address-area').text(),
				a.find('.address-location').text()
			);
			return false;
		});
		$('.address-page .page-title a').live('click',function(){
            if($(this).hasClass('return')){
				$('#js-cart-trolly-page').show().siblings().hide();
				document.body.scrollTop = $('#js-other-use-address').parent().prev().offset().top;
			}else{
				loadAddressInfo();
				$('#js-save').val('保存并选择');
				$('.showloading,#js-address-page').hide();
			}
			return false;
		});
		$('#js-address-info-page .page-title a').live('click',function(){
			$('#js-address-page').show().siblings().hide();
			if(!$('#js-address-page div.pxui-area a').length){
				$('#js-address-page .page-title a:first').click();
			}
			return false;
		});
	})();
	/*改变收货地址-end*/
	/*提交订单*/
	$('#js-trolly-form').submit(function(){
		if($("#js-submit-order").prop('disabled')){
			return false;
		}
		if(!sendData.paytype.type){
			alert('您还未选择支付方式，请先选择！');
			document.body.scrollTop = $('#js-paytype').offset().top-40;
			return false;
		}
		if(!window['VerifyPhone']){
			alert('您还未验证手机，请先验证！');
			document.body.scrollTop = $('#js-trolly').offset().top;
			$('#js-trolly-phone').focus();
			return false;
		}
		if(!$.trim($('#js-trolly-address-name').text())){
			alert('您还未选择收货地址，请先选择！');
			document.body.scrollTop = $('#js-other-use-address').parent().prev().offset().top;
			return false;
		}
		var isok = null;
		$('.js-grft-select').each(function(){
			if($(this).hasClass('pxui-bg-red')){
				isok = $(this).parent().parent().parent();
				return false;
			}
		});
    
		if(isok){
			if(!confirm('您有赠品尚未选择，是否确定放弃赠品并提交订单？')){
				document.body.scrollTop = isok.offset().top;
				return false;
			}
		}
              
   
            
		sendData.act = 'submit';
		sendData.phone = window['VerifyPhone'];
        sendData.code  = window['VerifyCode'];
		sendData.message = $.trim($('#js-trolly-message').val());
		sendData.img_code = $.trim($('#img_code').val())
		sendData.address = {
			id			:$.trim($('#js-trolly-address-id').val()),
			province	:$.trim($('#js-trolly-address-province').text()),
			city		:$.trim($('#js-trolly-address-city').text()),
			area		:$.trim($('#js-trolly-address-area').text()),
			phone		:$.trim($('#js-trolly-address-phone').text()),
			address		:$.trim($('#js-trolly-address-address').text()).replace(/\+/g,' '),
			name		:$.trim($('#js-trolly-address-name').text()).replace(/\+/g,' '),
			zipcode		:$.trim($('#js-trolly-address-zipcode').text())
		};
		var html = '<form method="post" action="'+$('#js-trolly-form').attr('action')+'">';
		$.each($.param(sendData).split('&'),function(index,value){
			value = value.split('=');
			html+='<input type="hidden" name="'+decodeURIComponent(value[0])+'" value="'+decodeURIComponent(value[1])+'"/>';
		});
		$('#js-trolly-form').unbind('submit').submit(function(){return false;});
		$("#js-submit-order").val('正在提交订单，请稍后...').prop('disabled',true);
		$(html+'</form>').appendTo('body').submit();
		return false;
	});
	/*提交订单-end*/
        
});

//以下为秒杀购物车 秒杀 js start
$(document).ready(function(e) {	
	if ($('#js-mbutton span').length>0) {
		var time = parseInt($('#js-mbutton span').attr("time"));
		$('#js-mbutton span').data("setInterval",setInterval(function(){
			if(--time==0){
				clearInterval($('#js-mbutton span').data("setInterval"));
				$('#js-mbutton span').remove();
				$('#js-mbutton input').addClass('ok');
				return false;
			}
			var h = parseInt(time/60/60);
			var m = parseInt(time/60) - h * 60;
			var s = time - m * 60 - h * 60 * 60;
			$('#js-mbutton span b:eq(0)').text(double(h));
			$('#js-mbutton span b:eq(1)').text(double(m));
			$('#js-mbutton span b:eq(2)').text(double(s));
		},1000));
	};	
	function double(n){
		return n>9?n:'0'+n;
	}
	
	
	$('#js-mbutton input').click(function(){
		if (!$(this).hasClass('ok'))return false;
		if ($('#fixed-win').length>0)$('#fixed-win').remove();
		if ($('#jquery_addmask').length>0)$('#fixed-win').remove();
		$.documentMask();
		$('#js-trolly').append('<div id="fixed-win" class="fixed-win" style="height:143px; margin-top:-61.5px"><div class="vcode"><p><input id="img_code"  type="text" placeholder="请输入验证码" name="verifycode"><img src="/register/vercode?is_num=1" class="verifyimg"></p><span></span></div><a href="#" id="vcodesubmit">确定</a></div>');
		$('#img_code').live('keydown',function(event){
			if(event.keyCode==13){ //回车失去焦点
				if($('#fixed-win .vcode input').val()==''){
					$('#fixed-win .vcode span').text('请输入验证码');
					return false;	
				}
				submitfrom();
			}
		});
		$('#jquery_addmask').live('click',function(){
			if ($('#fixed-win').length>0) $('#jquery_addmask,#fixed-win').remove();
		});
		return false;
	});
	
	$('#fixed-win a').live('click',function(){
		if ($(this).is('#vcodesubmit')){
			if($('#fixed-win .vcode input').val()==''){
				$('#fixed-win .vcode span').text('请输入验证码');
				return false;	
			}
			submitfrom();
		}else{
			if ($('#jquery_addmask').length>0) $('#jquery_addmask').fadeOut(function(){$('#jquery_addmask').remover()});
			if ($('#fixed-win').length>0) $('#fixed-win').fadeOut(function(){$('#fixed-win').remover()});
			$('#js-mbutton input').removeClass('ok');
		}
		return false;
	});
	
	function submitfrom(){
		$.ajax({
			url: '/register/vercode?code='+$('#fixed-win .vcode input').val()+'&act=v&is_num=1',
			type: 'GET',
			dataType: 'json',
			cache:false,
			timeout: 50000,
			error: function(data){alert(data);},
			success: function(data){
				if (data.IsSuccess){
					$('#js-trolly-form').submit();
				}else{
					$('#fixed-win .vcode span').text('验证码错误。');
				}
			}
		});	
	}
	
	$('#fixed-win .vcode input').live('focus',function(){$('#fixed-win .vcode span').text('');});
	
	$('.verifyimg').live('click',function(){
		var myDate = new Date();
		$(this).attr('src',$(this).attr('src').split('?')[0]+'?'+myDate.getMilliseconds()+"&"+$(this).attr('src').split('?')[1]);
	});
});

//以上为秒杀购物车 秒杀 js end